$(function(){ 
    
    showCart();
    
    // Update button
    $('#tblCartDetails').on('click', '#btnUpdateCart', function(){
        updateCart();
        return false;    
    });
    
    // Update checkout
    $('#tblCartDetails').on('click', '#btnCheckout', function(){
        if(confirm("Confirm to submit order?")) {
            $.cookies.del('cart');
            alert('Order sent. We will cotact you via phone as soon as possible.');
            location.href = 'cart.html';
        }
        return false;    
    });
    
    // Update months
    $('#tblCartDetails').on('change', '.months', function(){
        var val = parseInt($(this).val());
        var min = parseInt($(this).attr('data-min'));
        if(val < min) {
            alert('Minumum of months is ' + min);
            $(this).val(min);
        }   
    });
});

function showCart() {
    if($.cookies.get('cart') !== null) {
        cart = $.cookies.get('cart');
        
        if(cart.length > 0) {
            $('#tblCartDetails tfoot').show();   
        }
        
        var html = '';
        
        for(i = 0; i < cart.length; i++) {
            var item = cart[i];
            html += '<tr class="item" data-id="'+ item.id +'">';
            html += '<td class="aligncenter">'+ (i + 1) +'</td>';
            html += '<td>'+ item.name +'</td>';
            html += '<td class="alignright">$'+ item.price +'</td>';
            html += '<td class="aligncenter"><input type="text" class="months" name="months" value="'+ item.months +'" data-min="'+ item.minMonths +'"/></td>';
            var amount = parseInt(item.months) * parseFloat(item.price);
            html += '<td class="alignright">$'+ amount.toFixed(2) +'</td>';
            html += '<td class="aligncenter"><input type="checkbox" class="remove" name="remove"/></td>';
            html += '</tr>';
        }
        
        $('#tblCartDetails tbody').html(html);
    }
}

function updateCart() {
    if($.cookies.get('cart') !== null) {
        var cart = $.cookies.get('cart');
        
        $('#tblCartDetails tbody').find('tr.item').each(function(){
            var id = $(this).attr('data-id');
            
            for(i = 0; i < cart.length; i++) {
                if(id == cart[i].id) {
                    if($(this).find('.remove').is(':checked')) {
                        cart.splice(i, 1); // Remove item at i
                    } else {
                        cart[i].months = $(this).find('.months').val();
                    }
                }
            } 
        });
        
        if(cart.length > 0) {
            $.cookies.set('cart', JSON.stringify(cart));    
        } else {
            $.cookies.del('cart');
        }
        location.href = 'cart.html';
    }
}